<template>
  <base-container>
    <!-- 搜索栏 -->
    <avue-table-search
      :option="searchOption"
      v-model="searchParams"
      @search-change="loadTableSearch"
      @search-reset="loadTableSearchReset"
    />
    <!-- 卡片容器 -->
    <base-table-card>
      <template #header-left>
        <el-tabs v-model="searchParams.modelStatus" @tab-change="loadGetTableData">
          <el-tab-pane label="正常" :name="1" />
          <el-tab-pane label="已停用" :name="0" />
        </el-tabs>
      </template>
      <template #header-right>
        <el-button type="primary" @click="handleOpenAddDialog">新增型号</el-button>
      </template>
      <avue-crud
        ref="avueCrudRef"
        :option="tableOption"
        :data="tableData"
        v-model="formData"
        :page="page"
        :table-loading="tableLoading"
        :before-open="handleBeforeOpen"
        @refresh-change="loadGetTableData"
        @current-change="loadTablePageChange"
        @size-change="loadTablePageSizeChange"
        @row-save="loadAdd"
        @row-update="loadEdit"
      >
        <!-- 关联品牌：二级联动（第一级：name 品牌；第二级：categories 商品类目） -->
        <template #brandId-form>
          <div style="display: flex; gap: 12px; width: 100%">
            <el-select
              v-model="formData.brandId"
              placeholder="请选择品牌"
              @change="brandIdChange"
              clearable
              filterable
              style="flex: 1"
            >
              <el-option v-for="b in brandOptions" :key="b.value" :label="b.label" :value="b.value" />
            </el-select>
            <!-- <el-cascader
              v-model="formData.categories"
              :options="categoryOptions"
              :props="categoryProps"
              clearable
              filterable
              style="flex: 1"
            /> -->
          </div>
        </template>
        <template #categories-form>
          <div style="display: flex; gap: 12px; width: 100%">
            <el-cascader
              v-model="formData.categories"
              placeholder="请选择品牌的类目"
              :options="brandIdCategoryOptions"
              :props="categoryProps"
              clearable
              filterable
              style="flex: 1"
            />
          </div>
        </template>
        <template #attributes1-form>
          <!-- <FormSelectTree
            v-model="formData.attributes"
            :tree-data="menuTreeData"
            :tree-props="{ label: 'name', children: 'children' }"
          /> -->
          <el-cascader
            v-model="formData.attributes1"
            placeholder="请选择关联属性"
            :options="attributesOptions"
            :props="attributesProps"
            clearable
            filterable
            :style="{ width: '100%' }"
            @change="attributesChange1"
          />
        </template>
        <template #attributes2-form>
          <!-- <FormSelectTree
            v-model="formData.attributes"
            :tree-data="menuTreeData"
            :tree-props="{ label: 'name', children: 'children' }"
          /> -->
          <el-cascader
            v-model="formData.attributes2"
            placeholder="请选择关联属性"
            :options="attributesOptions"
            :props="attributesProps"
            clearable
            filterable
            :style="{ width: '100%' }"
            @change="attributesChange2"
          />
        </template>
        <template #menu="{ row }">
          <el-button type="primary" text @click="handleToggleDisplay(row)" v-if="row.modelStatus === 1">停用</el-button>
          <el-button type="primary" text @click="handleToggleDisplay(row)" v-else>启用</el-button>
          <el-button type="primary" text @click="handleEdit(row)">编辑</el-button>
          <el-button v-if="row.modelStatus === 0" type="danger" text @click="loadDel(row)"> 删除 </el-button>
        </template>
      </avue-crud>
    </base-table-card>
  </base-container>
</template>

<script setup>
  import Option from "@/crudOption/goods/model";
  import { ElMessageBox } from "element-plus";

  onMounted(() => {
    // 获取表格数据
    loadGetTableData();
    // 刷新品牌列表
    loadBrandOptions();
    // 刷新类目列表
    loadCategoryOptions();
    //获取属性管理
    loadAttributesOptions();
  });
  /* ================== 启用或停用（确认 + loading） ================== */
  async function handleToggleDisplay(row) {
    const nextVal = row.modelStatus === 1 ? 0 : 1;
    const msg = nextVal === 0 ? "确定要停用该型号吗？" : "确定要启用该型号吗？";

    try {
      await ElMessageBox.confirm(msg, "提示", { type: "warning" });
      row._statusLoading = true;
      await Api.goods.modelChange({ id: row.id, modelStatus: nextVal });
      // row.categoryStatus = nextVal; // 手动切换
      loadGetTableData();
      $msg.success(nextVal ? "已启用" : "已停用");
    } finally {
      row._statusLoading = false;
    }
  }
  // avue-crud 组件实例
  const avueCrudRef = ref({});

  // 增删改查 hook
  let {
    data: tableData,
    loading: tableLoading,
    page: page,
    search: searchParams,
    form: formData,
    get: loadGetTableData,
    add: loadAdd,
    edit: loadEdit,
    del: loadDel,
    pageNumChange: loadTablePageChange,
    pageSizeChange: loadTablePageSizeChange,
    searchReset: loadTableSearchReset,
    searchChange: loadTableSearch,
  } = useCrudHook({
    get: Api.goods.modelPage,
    add: Api.goods.modelAdd,
    edit: Api.goods.modelUpdate,
    del: Api.goods.modelDelete,
    search: { modelStatus: 1 },
    dataRes: "data.records",
    getParamsFormat: params => {
      console.log("🚀 ~ params:", params);
      // 新增时间
      if (params.createTime && params.createTime.length === 2) {
        params.createBeginTime = `${params.createTime[0]} 00:00:00`;
        params.createEndTime = `${params.createTime[1]} 23:59:59`;
        delete params.createTime;
      }
      // 编辑时间
      if (params.updateTime && params.updateTime.length === 2) {
        params.updateBeginTime = `${params.updateTime[0]} 00:00:00`;
        params.updateEndTime = `${params.updateTime[1]} 23:59:59`;
        delete params.updateTime;
      }
      // 返回查询参数
      return params;
    },
    addParamsFormat: row => ({
      ...row,
      categoryLevelOneId: row.categories[0],
      categoryLevelTwoId: row.categories[1],
      attributes1: (Array.isArray(row.attributes1) ? row.attributes1 : [])
        .map(p => (Array.isArray(p) && p.length >= 2 ? { levelOneId: Number(p[0]), levelTwoId: Number(p[1]) } : null))
        .filter(Boolean),
      attributes2: (Array.isArray(row.attributes2) ? row.attributes2 : [])
        .map(p => (Array.isArray(p) && p.length >= 2 ? { levelOneId: Number(p[0]), levelTwoId: Number(p[1]) } : null))
        .filter(Boolean),
    }),
    editParamsFormat: row => ({
      ...row,
      categoryLevelOneId: row.categories[0],
      categoryLevelTwoId: row.categories[1],
      attributes1: (Array.isArray(row.attributes1) ? row.attributes1 : [])
        .map(p => (Array.isArray(p) && p.length >= 2 ? { levelOneId: Number(p[0]), levelTwoId: Number(p[1]) } : null))
        .filter(Boolean),
      attributes2: (Array.isArray(row.attributes2) ? row.attributes2 : [])
        .map(p => (Array.isArray(p) && p.length >= 2 ? { levelOneId: Number(p[0]), levelTwoId: Number(p[1]) } : null))
        .filter(Boolean),
    }),
  });

  // 获取 搜索配置 和 表格配置
  const { searchOption, tableOption } = Option(formData);

  // 弹窗打开前
  const handleBeforeOpen = async done => {
    // 刷新品牌列表
    await loadBrandOptions();
    // 刷新类目列表
    await loadCategoryOptions();
    //获取属性管理
    loadAttributesOptions();
    nextTick(done);
  };

  // 品牌选项
  const brandOptions = ref([]);
  let brandOptionsData = [];
  const loadBrandOptions = async () => {
    try {
      const res = await Api.goods.brandPage({ pageNumber: 1, pageSize: 9999, brandStatus: 1 });
      const rows = res?.data?.records || res?.data?.data?.records || [];
      brandOptions.value = rows.map(i => ({ label: i.name || i.brandName || `#${i.id}`, value: i.id }));
      brandOptionsData = rows;
    } catch {
      brandOptions.value = [];
    }
  };

  // 二级类目（商品类目，用于 categories）
  const categoryOptions = ref([]);
  const categoryProps = { value: "id", label: "name", children: "children", emitPath: true };
  const loadCategoryOptions = async () => {
    try {
      const res = await Api.goods.categoryList({ pageNumber: 1, pageSize: 9999 });
      const rows = res?.data?.records || res?.data?.data?.records || [];
      categoryOptions.value = rows;
    } catch {
      categoryOptions.value = [];
    }
  };
  const brandIdCategoryOptions = ref([]);
  // 选择品牌后关联类目
  const brandIdChange = val => {
    brandIdCategoryOptions.value = [];
    brandOptionsData.forEach(i => {
      if (i.id == val) {
        if (i.categories.length > 0) {
          categoryOptions.value.forEach(k => {
            let obj = {};
            i.categories.forEach(j => {
              if (j.levelOneId == k.id) {
                if (j.levelOneId != obj.id) {
                  obj = {
                    id: k.id,
                    name: k.name,
                    children: [],
                  };
                  k.children.forEach(l => {
                    if (j.levelTwoId == l.id) {
                      obj.children.push({
                        id: l.id,
                        name: l.name,
                      });
                    }
                  });
                } else {
                  k.children.forEach(l => {
                    if (j.levelTwoId == l.id) {
                      obj.children.push({
                        id: l.id,
                        name: l.name,
                      });
                    }
                  });
                }
              }
            });
            if (Object.keys(obj).length > 0) {
              // console.log("🚀 ~ brandIdChange ~ obj:", obj);
              brandIdCategoryOptions.value.push(obj);
            }
          });
        }
      }
    });
  };
  // 关联属性
  const attributesProps = {
    multiple: true,
    checkStrictly: false,
    emitPath: true,
    value: "id",
    label: "attributeName",
    children: "subsets",
  };
  const attributesOptions = ref([]);

  // 分类树由接口返回，构造函数已移除

  async function loadAttributesOptions() {
    try {
      const res = await Api.goods.getAttributeList({ pageNumber: 1, pageSize: 9999 });
      const rows = res?.data || [];
      attributesOptions.value = rows;
      console.log("🚀 ~ loadAttributesOptions ~ attributesOptions:", attributesOptions.value);
    } catch {
      attributesOptions.value = [];
    }
  }
  const attributesChange1 = val => {
    // console.log("🚀 ~ attributesChange1 ~ val:", val);
    if (val.length > 1 && val[val.length - 1][0] != val[0][0]) {
      let arr = [];
      val.forEach(item => {
        arr.push(item[0]);
      });
      if (arr.length > 1) {
        let index = findDifferentValueStart(arr);
        if (index > 0) {
          formData.value.attributes1 = [];
          formData.value.attributes1 = val.slice(index, val.length);
        }
      }
    }
  };
  const attributesChange2 = val => {
    // console.log("🚀 ~ attributesChange2 ~ val:", val);
    if (val.length > 1 && val[val.length - 1][0] != val[0][0]) {
      let arr = [];
      val.forEach(item => {
        arr.push(item[0]);
      });
      if (arr.length > 1) {
        let index = findDifferentValueStart(arr);
        if (index > 0) {
          formData.value.attributes2 = [];
          formData.value.attributes2 = val.slice(index, val.length);
        }
      }
    }
  };
  const findDifferentValueStart = arr => {
    for (let i = 1; i < arr.length; i++) {
      if (arr[i] !== arr[i - 1]) {
        return i; // 返回第一个与前一个元素不同的位置
      }
    }
    return -1; // 如果全部相同则返回-1
  };
  // 打开新增弹窗
  const handleOpenAddDialog = () => {
    formData.value = { ...formData.value };
    avueCrudRef.value.rowAdd();
  };
  // 将后端返回的 categories 回显为级联需要的路径数组
  function mapCategoriesToPaths1(row) {
    const l1 = row?.categoryLevelOneId;
    const l2 = row?.categoryLevelTwoId;
    if (l1 == null || l2 == null) return null;
    return [Number(l1), Number(l2)];
  }
  // 将后端返回的 categories 回显为级联需要的路径数组
  function mapCategoriesToPaths2(categories) {
    if (!Array.isArray(categories)) return [];
    return categories
      .map(i => {
        const l1 = i?.levelOneId;
        const l2 = i?.levelTwoId;
        if (l1 == null || l2 == null) return null;
        return [Number(l1), Number(l2)];
      })
      .filter(Boolean);
  }

  // 编辑时回显数据
  function handleEdit(row) {
    const paths1 = mapCategoriesToPaths1(row);
    const paths2 = mapCategoriesToPaths2(row?.attributes1);
    const paths3 = mapCategoriesToPaths2(row?.attributes2);
    row.brandId = Number(row.brandId);
    brandIdCategoryOptions.value = [];
    brandOptionsData.forEach(i => {
      if (i.id == row.brandId) {
        if (i.categories.length > 0) {
          categoryOptions.value.forEach(k => {
            let obj = {};
            i.categories.forEach(j => {
              if (j.levelOneId == k.id) {
                if (j.levelOneId != obj.id) {
                  obj = {
                    id: k.id,
                    name: k.name,
                    children: [],
                  };
                  k.children.forEach(l => {
                    if (j.levelTwoId == l.id) {
                      obj.children.push({
                        id: l.id,
                        name: l.name,
                      });
                    }
                  });
                } else {
                  k.children.forEach(l => {
                    if (j.levelTwoId == l.id) {
                      obj.children.push({
                        id: l.id,
                        name: l.name,
                      });
                    }
                  });
                }
              }
            });
            if (Object.keys(obj).length > 0) {
              // console.log("🚀 ~ brandIdChange ~ obj:", obj);
              brandIdCategoryOptions.value.push(obj);
            }
          });
        }
      }
    });
    row.categories = paths1;
    row.attributes1 = paths2;
    row.attributes2 = paths3;
    avueCrudRef.value?.rowEdit({
      ...row,
    });
  }
</script>
<style lang="scss" scoped></style>
